﻿using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Mofang.Utils.LogProvider
{
	/// <summary>
	/// TODO:
	/// </summary>
	/// <typeparam name="T">Only for Log</typeparam>
	public class LogRepository<T> where T : ICommonLog
	{	
		/// <summary>
		/// 获取EF Context
		/// </summary>
		/// <returns></returns>
		public IDbConnection GetConnection()
		{
			
			return ConnectionService.GetMySqlConnection();			
			
		}

		/// <summary>
		/// 查询单条日志
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		public T Get(string id)
		{

			using (var conn = GetConnection())
			{
				string Table = typeof(T).Name;

				var sqlCmd = string.Format("select * from {0} where Id=@id", Table);

				var log = conn.Query<T>(sqlCmd, new { id = id }).FirstOrDefault();

				return log;
			}

			
		}

		/// <summary>
		/// 批量查询日志
		/// </summary>
		/// <param name="whereExp">Id=@id</param>
		/// <param name="param">new {id= logId }</param>
		/// <returns>T 必须是CLSS</returns>
		public List<T> BatchGet(string whereExp,object param)
		{
			using (var conn = GetConnection())
			{
				string Table = typeof(T).Name;

				var sqlCmd = string.Format("select * from {0} where {1}", Table, whereExp);

				var logs = conn.Query<T>(sqlCmd, param).ToList();

				return logs;
			}
			
		}

		/// <summary>
		/// 新增日志
		/// </summary>
		/// <param name="t"></param>
		/// <returns></returns>
		public int Insert(T t)
		{
			string query = string.Format("INSERT INTO {0}(Id,Type,Operation,Message,IsSuccess,UserId,UserName,RelationId,OrgId,Client,Server,Created)VALUES(@Id,@Type,@Operation,@Message,@IsSuccess,@UserId,@UserName,@RelationId,@OrgId,@Client,@Server,@Created)"
				, t.GetType().Name);

			using (var conn = GetConnection())
			{
				var result=conn.Execute(query, t);

				return result;

			}

		}


		

	}

	
}
